<template>
  <div
    class="PlayListMsg" ref="PlayListMsg" :style="{
      '--color1': color1,
      '--color2': color2,
      '--color3': color3,
    }">
    <canvas id="myCanvas" ref="MyCanvas"></canvas>
    <!-- 左边图片 -->
    <p class="playImg">
      <img :src="playListMsg.al.picUrl" alt="" width="200" height="200" crossorigin="anonymous"   @load="loadImage" ref="imgs"/>
      <!-- <img :src="playListMsg.al.picUrl" alt="" width="200" height="200" crossorigin="anonymous"   ref="imgs"/> -->
    </p>
    <!-- 右边部分 -->
    <div class="PlaylistRight">
      <div class="PlaylistRightMsg">
        <p class="ListMsgName">
          {{ playListMsg.name }}
        </p>
        <div class="xiangqing">
          <p class="ListMsgArName">
            歌手：
            <span v-for="(item, index) in playListMsg.ar" :key="item.id">
              {{ item.name }}
              <span v-if="index != playListMsg.ar.length - 1"> / </span>
            </span>
          </p>
          <p class="puthTime">发行时间：{{ createTime }}</p>
        </div>
      </div>
      <div class="PlaylistRightlyric" ref="PlaylistRightlyric">
          <ul class="lyricUl" ref="lyricUl">
          </ul>
      </div>
      <!-- <div class="PlaylistRightlyric" ref="scroll" :style="{
        '--fontcolor': fontColor,
        '--activeColor': activeColor,
      }">
        <p
          v-for="(item, index) in lyriclist"
          :key="index"
          :class="{
            active:
              currentTime * 1000 + 200 > item.time && currentTime * 1000 +200 < item.pre,
          }"
        >
          {{ item.lrc }}
        </p>
      </div> -->
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import ColorThief from "colorthief";
export default {
  data() {
    return {
      lyriclist: null,
      valTimer: null,
      color1:'0',
      color2:'0',
      color3:'0',
      fontColor:'#000',
      activeColor:'#fff',
      flag:false
    };
  },
  computed: {
    ...mapState({
      playList: (state) => state.PlaylistDetails.playList,
      playListIndex: (state) => state.PlaylistDetails.playListIndex,
      currentTime: (state) => state.PlaylistDetails.currentTime,
      duration: (state) => state.PlaylistDetails.duration,
      lyric: (state) => state.PlaylistDetails.lyric,
     
    }),
    playListMsg() {
      return this.playList[this.playListIndex];
    },
    createTime() {
      let date = new Date(this.playList[this.playListIndex].publishTime);
      let Y = date.getFullYear();
      let M = date.getMonth() + 1;
      M = M < 10 ? "0" + M : M;
      var D = date.getDate();
      D = D < 10 ? "0" + D : D;

      return `${Y}-${M}-${D}`;
    },
  },
  watch: {
    lyric() {
      this.generateLrc();
    },
    currentTime() {

      this.setOffset()
      // // 获取正在播放的字段
      // const p = document.querySelector("p.active");
      
      // // 获取当前滚动条
      // const scroll = this.$refs.scroll;
      // // 获取当前滚动条的上高度
      // let scrollTop = scroll.scrollTop;
      // // 获取滚动条的高度
      // let scrollHeight = scroll.scrollHeight;
      // let offsetHeight = Math.ceil(scroll.getBoundingClientRect().height);
      // // 当前高度
      // let currentHeight = scrollTop + offsetHeight;
      // // p距离盒子的高度 如果大于350px
      // if (p && p.offsetTop > 300) {
      //   // console.log('w未改变',scroll.scrollTop);
      //   // 改变前的值scroll.scrollTop
      //   // 改变后的值p.offsetTop-350
      //   this.animation(300,scroll.scrollTop,p.offsetTop-350,(val)=>{
      //     this.$refs.scroll.scrollTop = val;
      //   })
      //   // clearInterval(this.valTimer);
      //   // if (scroll.scrollTop !== p.offsetTop - 300) {
      //   //   clearInterval(this.valTimer);
      //   //   this.valTimer = setInterval(() => {
      //   //     scroll.scrollTop = scroll.scrollTop + 1;
      //   //     console.log("播放");
      //   //     if (scroll.scrollTop >= p.offsetTop - 300) {
      //   //       clearInterval(this.valTimer);
      //   //       console.log("停止");
      //   //     } else if (currentHeight >= scrollHeight) {
      //   //       clearInterval(this.valTimer);
      //   //     }
      //   //   }, 20);
      //   // }
      // }
    },
    playListIndex() {
      // setTimeout(() => {
      //   const scroll = this.$refs.scroll;
      //   scroll.scrollTop = 0;
      //   // // 默默奇妙要清除2次
      //   // clearInterval(this.valTimer);
      //   // clearInterval(this.valTimer);
      // }, 500);
     this.generateLrc()
    },
  },
  methods: {
    // LRC格式歌词的处理
    lyrics() {
      let arr=[];
       this.lyric.split(/[\r\n]+/).forEach((item) => {
        let min = item.slice(1, 3);
        let sec = item.slice(4, 6);
        let mill = item.slice(7, 10);
        let lrc = item.slice(11, item.length);
        if (isNaN(Number(mill))) {
          mill = item.slice(7, 9);
          lrc = item.slice(10, item.length);

        }
        let time = parseInt(min) * 60 * 1000 + parseInt(sec) * 1000 + parseInt(mill);
        if (lrc!='') {
          arr.push({
            min,
            sec,
            mill,
            lrc,
            time,
          })
        }
          
      });
      arr.forEach((item, i) => {
        if (i === arr.length - 1 || isNaN(arr[i + 1].time)) {
          item.pre = 100000;
        } else {
          item.pre = arr[i + 1].time;
        }
      });
      this.lyriclist = arr;
      console.log(this.lyriclist);
      return this.lyriclist;
    },
    // 渲染歌词
    generateLrc(){
      const lyc = this.lyrics();//歌词处理
      console.log(lyc,'当前歌词');
      let frag = document.createDocumentFragment();
      for (let i = 0; i < lyc.length; i++) {
        // 创建节点
        let li = document.createElement("li");
        // 写入歌词文本
        li.textContent = lyc[i].lrc
        // 插入歌词
        frag.appendChild(li)
        // 获取ul节点
        let ul =this.$refs.lyricUl
        // 插入到ul去
        // 将歌词清空 然后插入
        Promise.resolve(ul.innerHTML='').then(()=>{
          ul.appendChild(frag);
        })
        console.log('li1');
      }
      console.log('歌词变动');

    },
    // 获取需要高亮的行
    findIndex(){
        //  当前时间
        let currentTime = this.currentTime
        // 查询第一个满足条件的值
        let index = this.lyriclist.findIndex(e=> e.time>=currentTime*1000+500)
        if (index===-1) {
          index= this.lyriclist.length
        }
        // 返回下标
      return index-1
    },
    // 设置高亮和ul偏移
    setOffset(){
      // 获取容器高度
      const lycHeight = this.$refs.PlaylistRightlyric.clientHeight
      // 
      const liHeight=this.$refs.lyricUl.children[0].clientHeight
      // 设置最大偏移量
      const maxOffset = this.$refs.lyricUl.clientHeight - lycHeight;

      // 获取需要高亮的行的下标
      const index = this.findIndex()
      // 偏移量
      let offset = liHeight*index + liHeight/2 - lycHeight/2
      // 不需要偏移
      if (offset<0){
        offset = 0
        // 歌词末尾 不需要偏移
      }else if(offset>maxOffset){
        offset = maxOffset
      }
      // this.$refs.lyricUl.style.transform = `translateY(-${offset}px)`
      let from =this.$refs.PlaylistRightlyric.scrollTop
      let to = offset
      // if (this.$refs.PlaylistRightlyric.scrollTop>offset) {
      //     to = this.$refs.PlaylistRightlyric.scrollTop
      //     from =offset
      // }
      
      this.animation(500,from,to,(item)=>{
        if (this.$refs.PlaylistRightlyric) {
          this.$refs.PlaylistRightlyric.scrollTop=item
        }
        
      },this.flag)
     
      // 去掉之前高亮歌词
      let li = document.querySelector('.active')
      // 如果存在则删除
      if (li) {
        li.classList.remove('active')
      }
      // 不存在则添加
      this.$refs.lyricUl.children[index]?.classList.add('active')

    },
    /**
     * 
     * @param {number} duration 几秒 
     * @param {number} from 初始值 
     * @param {number} to 目标值
     * @param {funciton} callback  操作动画干什么
     * @param {boolean} flag  是否暂停
     */
    animation(duration,from,to,callback,flag){
      if(flag){
        return
      }
      const speed = (Math.abs(to-from)) / duration;
      const startime = Date.now();
      let val = from;

     let gundong =  setInterval(() => {
        const now = Date.now();
        const time = now - startime
        // 正向
        if (from<=to) {
          if (val>=to) {
            val = to;
            callback&&callback(val)
            clearInterval(gundong);
            return;
          }
          else if (time >=duration) {
            val = to;
            callback&&callback(val)
            clearInterval(gundong);
            return;
          }
          val = from + speed * time    
          callback&&callback(val)
          // 反向
        }else{
          if (val<=to) {
            val = to;
            callback&&callback(val)
            clearInterval(gundong);
            return;
          } 
          else if (time >=duration) {
            val = to;
            callback&&callback(val)
            clearInterval(gundong);
            return;
          }
          val = from - speed * time    
          callback&&callback(val)
        }
      }, speed);
     
    },
    canvasimg(){
      const canvas = this.$refs.MyCanvas;
      const width = this.$refs.PlayListMsg.clientWidth;
      const height = this.$refs.PlayListMsg.clientHeight;
      // 绘制宽高
      canvas.width = width
      canvas.height = height
      const ctx = canvas.getContext("2d");
      // ctx.fillStyle = "black";
      // ctx.fillRect(0, 0, width, height);
      // 图像处理
      let imgarr=[
        {x:0,y:0,width: width, height: height},
        {x:width/2-100,y:height/2-300,width:400,height:400},
        {x:width/4-100,y:height/4-100,width:300,height:300},
        {x:width/8-100,y:height/8-100,width:200,height:200},
        {x:width/12-150,y:height/12-450,width:200,height:200},
      ]
    
      let img =new Image();
      img.src  = `${this.playListMsg.al.picUrl}`
      img.onload =()=>{
        ctx.save()
        for (let i = 0; i < imgarr.length; i++) {
          if (i!==0) {
            ctx.translate(imgarr[i].x-imgarr[i].width/2,imgarr[i].y-imgarr[i].height/2);//设置画布上的(0,0)位置，也就是旋转的中心点
	          ctx.rotate(35*Math.PI/180);
          }
          ctx.filter='blur(80px)'
          ctx.drawImage(img,imgarr[i].x,imgarr[i].y,imgarr[i].width,imgarr[i].height);
        }
      }
    

    },
    // 图片加载背景渐变
     loadImage(){
      this.canvasimg()
    //   let colorthief = new ColorThief();
    //   let colors =  await  colorthief.getPalette(this.$refs.imgs,3)
    //   // 颜色
    //   let  colorss =  colors.map(c =>`rgb(${c[0]},${c[1]},${c[2]})`)
    //   // 判断颜色是否过暗或者过浅
    //     let arr = colorss[1].replace('rgb(','').replace(')','').split(',').map(Number);
    //     console.log(arr);
    //     var grayLevel = arr[0] * 0.299 + arr[1] * 0.587 + arr[2] * 0.114;
    //     if (grayLevel >= 192) {
    //       colorss[1]= `rgba(${arr[0]},${arr[1]},${arr[2]},0.8)`
    //     } else {
    //       colorss[1]= `rgba(${arr[0]},${arr[1]},${arr[2]},1)`
    //     }
      
      
    //   this.color1 = colorss[0]
    //   this.color2 = colorss[1]
    //   this.color3 = colorss[2]
            
    }
  },
  mounted() {
    this.generateLrc();
    const lycBox = this.$refs.PlaylistRightlyric
    let setFlag = null
    lycBox.addEventListener('wheel',()=>{
      // 防抖 歌词滚动
      console.log('11112312');
        clearTimeout(setFlag)
        this.flag=true
        setFlag = setTimeout(() => {
          this.flag=false
        }, 3000);
    })
    this.canvasimg();
    window.addEventListener('resize',()=>{
      if (this.$refs.PlayListMsg) {
        this.canvasimg()
      }
    });
  },
};
</script>

<style lang="less">

@keyframes rotateCanvas{
    0%{
      transform: rotate(0);
    }
    100%{
      transform: rotate(360deg);
    }
  }
.PlayListMsg {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: calc(100vh - 61px);
  // background-image: linear-gradient(45deg, #FF0000,#FFF200, #1E9600);
  // background-image: radial-gradient(var(--color1), var(--color2));
  // background:linear-gradient(45deg,var(--color1),  var(--color2));
  #myCanvas{
    position: absolute;

    width: 100%;
    z-index: -1000;
  }
  
  .playImg {
    width: 400px;
    aspect-ratio: 16/16;
    img {
      width: 100%;
      border-radius: 20px;

      height: 100%;
    }
  }
  .PlaylistRight {
    width: 600px;
    padding: 5% 0;
    .PlaylistRightMsg {
      .ListMsgName {
        font-size: 24px;
        color: #fff;
        padding-bottom: 10px;
        text-align: center;
      }
      .xiangqing {
        display: flex;
        vertical-align: middle;
        justify-content: center;
        color: #fff;

        .ListMsgArName {
          font-size: 14px;
          padding-right: 10px;
        }
        .puthTime {
          font-size: 14px;
        }
      }
    }
    .PlaylistRightlyric {
      width: 100%;
      height: 65vh;
      text-align: center;
      margin: 10px;
      overflow-x: hidden;
      transition: all 0.5s;
      ul{
        transition: all 0.5s;
        li{
          width: 100%;
          height: 30px;
          line-height: 30px;
          color: #aaa;
          text-shadow: 1px 1px 10px #aaa;
          transition: all .8s;
          &.active{
            color: #fff;
            transform: scale(1.2);
            text-shadow: 1px 1px 10px #ccc;
          }
        }
      }
    }
    .PlaylistRightlyric::-webkit-scrollbar {
      display: none;
    }
  }
}

</style>
